<?php

namespace app\common\middleware;

use think\Request;
use think\Response;

class AllowCrossDomain extends \think\middleware\AllowCrossDomain
{
    /**
     * 允许跨域请求
     * @access public
     * @param Request $request
     * @param \Closure $next
     * @param array|null $header
     * @return Response
     */
    public function handle($request, \Closure $next, ?array $header = [])
    {
        $header = !empty($header) ? array_merge($this->header, $header) : $this->header;
        $header['Access-Control-Allow-Headers'] = 'Authorization,WebRouter,Origin,App, X-Requested-With, Content-Type, Accept';
        unset($header['Access-Control-Allow-Origin']);
        $origin = $request->header('origin');
//        $referer = $request->header('Referer');
//        if (!empty($referer)){
//            $header['Access-Control-Allow-Origin'] = $referer;
//        }else {
            if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) {
                $header['Access-Control-Allow-Origin'] = $origin;
            } else {
                $header['Access-Control-Allow-Origin'] = '*';
            }
//        }
        return $next($request)->header($header);
    }
}
